package vip.liux.backend.infrastructure.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Configuration(proxyBeanMethods = false)
public class SpringAiConfig {

    @Bean
    ChatClient chatClient(ChatClient.Builder builder) {
        return builder.defaultSystem("你是一个智能机器人,你的名字叫 Spring AI智能机器人").build();
    }

    @Bean
    RedisChatMemory redisChatMemory(RedisTemplate<Object, Object> redisTemplate) {
        return new RedisChatMemory(redisTemplate);
    }

    public static class RedisChatMemory implements ChatMemory {

        private final RedisTemplate<Object, Object> redisTemplate;
        private final ObjectMapper objectMapper = new ObjectMapper();

        public RedisChatMemory(RedisTemplate<Object, Object> redisTemplate) {
            this.redisTemplate = redisTemplate;
        }

        @Override
        public void add(String conversationId, List<Message> messages) {
            try {
                for (Message message : messages) {
                    String json = objectMapper.writeValueAsString(message);
                    redisTemplate.opsForList().rightPush(conversationId, json);
                }
            } catch (Exception e) {
                throw new RuntimeException("消息写入 Redis 失败", e);
            }
        }

        @Override
        public List<Message> get(String conversationId, int lastN) {
            try {
                Long size = redisTemplate.opsForList().size(conversationId);
                if (size == null || size == 0) {
                    return List.of();
                }
                long start = Math.max(0, size - lastN);
                List<Object> jsonList = redisTemplate.opsForList().range(conversationId, start, size - 1);
                List<Message> result = new ArrayList<>();
                if (jsonList != null) {
                    for (Object obj : jsonList) {
                        if (obj instanceof String json) {
                            Message msg = objectMapper.readValue(json, Message.class);
                            result.add(msg);
                        }
                    }
                }
                return result;
            } catch (Exception e) {
                throw new RuntimeException("从 Redis 读取消息失败", e);
            }
        }

        @Override
        public void clear(String conversationId) {
            redisTemplate.delete(conversationId);
        }
    }
}
